package com.example.asus.testskip;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;

public class MyReceiver extends BroadcastReceiver {
    public final String TAG = "MyReceiver";
    private WindowManager mWinMgr;
    private TextView mTxtView;

    public MyReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "intent.action=" + intent.getAction());
        if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
            String phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            int state = telephony.getCallState();
            Log.e(TAG, "state=" + state + ",phoneNumber=" + phoneNumber);
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    Log.e(TAG, "CALL_STATE_RINGING=" + state);
                    callView(context, phoneNumber);
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Log.e(TAG, "CALL_STATE_OFFHOOK=" + state);
                    if (mWinMgr != null) {
                        mWinMgr.removeView(mTxtView);
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.e(TAG, "CALL_STATE_IDLE=" + state);
                    if (mWinMgr != null) {
                        mWinMgr.removeView(mTxtView);
                    }
                    break;
                default:
                    Log.e(TAG, "default state=" + state);
                    if (mWinMgr != null) {
                        mWinMgr.removeView(mTxtView);
                    }
                    break;
            }
        }
    }

    private void callView(Context context, String phoneNumber) {
        mWinMgr = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        params.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.format = PixelFormat.RGBA_8888;
        mTxtView = new TextView(context);
        mTxtView.setText("悬浮窗，来电号码：" + phoneNumber);
        //mTxtView.setBackgroundColor(0x00000000);
        mTxtView.setTextColor(0xFFFFFFFF);
        mWinMgr.addView(mTxtView, params);
    }
}